package com.zut.chat.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;

/**
 * 表情包代理控制器
 */
@Slf4j
@RestController
@RequestMapping("/api/sticker")
@CrossOrigin(origins = "*")
public class StickerController {

        /**
     * 代理获取表情包列表
     */
    @GetMapping("/list")
    public ResponseEntity<String> getStickerList(
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "16") int perPage,
            @RequestParam(defaultValue = "changyong") String keyword,
            @RequestParam(defaultValue = "wx2f23b155ee1d2ae1") String appId) {
        
        String apiUrl = String.format(
            "https://a.biaoqing.site/storage/emote/random?app_id=%s&page=%d&per_page=%d&keyword=%s",
            appId, page, perPage, keyword
        );

        log.info("代理请求表情包API: {}", apiUrl);

        try {
            URL url = new URL(apiUrl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();

            // 设置请求方法
            connection.setRequestMethod("GET");

            // 设置请求头 - 模拟微信小程序环境
            connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/132.0.0.0 Safari/537.36 MicroMessenger/7.0.20.1781(0x6700143B) NetType/WIFI MiniProgramEnv/Windows WindowsWechat/WMPF WindowsWechat(0x63090a13) UnifiedPCWindowsWechat(0xf254100e) XWEB/16389");
            connection.setRequestProperty("encrypted", "");
            connection.setRequestProperty("timestamp", String.valueOf(System.currentTimeMillis()));
            connection.setRequestProperty("xweb_xhr", "1");
            connection.setRequestProperty("form-token", "");
            connection.setRequestProperty("user-token", "FF9A02580F62455F9B2B08DED4A0F806MDAwMDAwMDAwMLKqu3qyzoq6ipK5k7SWyZmvqo9sgY2skbaqnKeEfp1muXS-Z7Onbb2FkpNv");
            connection.setRequestProperty("client-type", "applet");
            connection.setRequestProperty("secret", "");
            connection.setRequestProperty("app-mode", "api");
            connection.setRequestProperty("content-type", "application/json");
            connection.setRequestProperty("app-id", "");
            connection.setRequestProperty("plaform-type", "weixin");
            connection.setRequestProperty("version", "1.0.0");
            connection.setRequestProperty("sec-fetch-site", "cross-site");
            connection.setRequestProperty("sec-fetch-mode", "cors");
            connection.setRequestProperty("sec-fetch-dest", "empty");
            connection.setRequestProperty("referer", "https://servicewechat.com/wx2f23b155ee1d2ae1/2/page-frame.html");
            connection.setRequestProperty("accept-language", "zh-CN,zh;q=0.9");
            connection.setRequestProperty("priority", "u=1, i");
            connection.setRequestProperty("Accept", "application/json, text/plain, */*");

            // 设置连接超时和读取超时
            connection.setConnectTimeout(10000);
            connection.setReadTimeout(30000);

            // 获取响应码
            int responseCode = connection.getResponseCode();
            log.info("API响应码: {}", responseCode);

            // 读取响应内容
            BufferedReader reader;
            if (responseCode >= 200 && responseCode < 300) {
                reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8));
            } else {
                reader = new BufferedReader(new InputStreamReader(connection.getErrorStream(), StandardCharsets.UTF_8));
            }

            StringBuilder response = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                response.append(line);
            }
            reader.close();
            connection.disconnect();

            String responseBody = response.toString();
            log.info("API响应内容: {}", responseBody);

            if (responseCode >= 200 && responseCode < 300) {
                return ResponseEntity.ok()
                        .header("Content-Type", "application/json;charset=UTF-8")
                        .body(responseBody);
            } else {
                log.error("API请求失败，响应码: {}, 响应内容: {}", responseCode, responseBody);
                return ResponseEntity.status(HttpStatus.BAD_GATEWAY)
                        .header("Content-Type", "application/json;charset=UTF-8")
                        .body("{\"code\": 502, \"message\": \"上游API请求失败\", \"data\": null}");
            }

        } catch (Exception e) {
            log.error("代理请求表情包API异常", e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .header("Content-Type", "application/json;charset=UTF-8")
                    .body("{\"code\": 500, \"message\": \"代理请求异常: " + e.getMessage() + "\", \"data\": null}");
        }
    }
}
